import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


class MyModelBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):

        # 判断是否从前端服务器请求登录
        if not request:
            try:
                user = User.objects.get(username=username, is_superuser=True, is_staff=True)
            except:
                return None
            else:
                if user.check_password(password):
                    return user
                return None

        # 1 判断是否为手机格式
        try:
            if re.match('^1[3-9]\d{9}$', username):

                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except Exception as e:
            return None

        # 2 校验密码

        if user.check_password(password):
            return user
        else:
            return None
